import service from '@/utils/request'
import { getStudentCourseList } from '@/api/course' // 导入正确的获取课程列表接口

// 获取课程的问卷
export const surveyListService = (courseManageId) => {
  return service({
    url: '/survey/stulistAll',
    method: 'get',
    params: {
      courseManageId: courseManageId
    }
  });
};

//添加问卷
// 修改 addSurveyService 以接受 config 参数
export const addSurveyService = (data) => {
  const params = new URLSearchParams()
  for (let key in data) {
    params.append(key,data[key]);
  }
  return service.post('/survey', params);
};

// 获取问卷统计数据
export const getFeedbackStats = async () => {
  try {
    // 1. 获取学生的所有课程
    const coursesResult = await getStudentCourseList();
    console.log('获取到的课程列表:', coursesResult);

    if (coursesResult.code !== 0 || !coursesResult.data) {
      throw new Error('获取课程列表失败');
    }

    // 2. 获取所有课程的问卷
    let totalCount = 0;
    let completedCount = 0;

    // 遍历每个课程
    for (const course of coursesResult.data) {
      try {
        const result = await surveyListService(course.courseManageId);
        console.log(`课程 ${course.courseManageId} 的问卷数据:`, result);

        if (result.code === 0 && result.data) {
          const surveys = result.data;
          totalCount += surveys.length;
          // 统计 state 为 "已填写" 的问卷数量
          completedCount += surveys.filter(item => item.state === '已填写').length;
        }
      } catch (error) {
        console.error(`获取课程 ${course.courseManageId} 的问卷失败:`, error);
      }
    }

    console.log('问卷统计结果:', { total: totalCount, completed: completedCount });

    return {
      code: 0,
      data: {
        total: totalCount,
        completed: completedCount
      }
    };
  } catch (error) {
    console.error('获取问卷统计失败:', error);
    return {
      code: -1,
      message: error.message
    };
  }
};

// 获取所有问卷列表
export const getFeedbackList = () => {
  return service({
    url: '/survey/stulistAll',
    method: 'get'
  });
};
